﻿using EnterpriseWebsiteApi.Dto.Carousel;
using EnterpriseWebsiteBLL;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EnterpriseWebsiteApi.ActionResults;
using EnterpriseWebsiteEntity;
using EnterpriseWebsiteUtil.Helper;
using System.IO;
using EnterpriseWebsiteApi.ActionFilters;

namespace EnterpriseWebsiteApi.Controllers.Admin
{
    [ApiController]
    [Route("api/admin/[controller]/[action]")]
    [TypeFilter(typeof(JwtAuthorizeFilter))]
    public class CarouselController : ControllerBase
    {
        private readonly CarouselService _carouselService;
        private readonly Mapper _mapper;

        public CarouselController(CarouselService carouselService, Mapper mapper)
        {
            _carouselService = carouselService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取全部轮播图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<CarouselDto>> GetAllCarousels()
        {
            try
            {
                var entities = _carouselService.GetAllCarousels();
                var dtos = _mapper.MapList<CarouselDto>(entities);
                return new Success(dtos);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 根据ID获取一个轮播图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<CarouselDto> GetCarouselById(int id)
        {
            try
            {
                var entity = _carouselService.GetCarouselById(id);
                if (entity == null)
                {
                    return new Error(new Exception($"Id {id} 轮播图不存在"));
                }
                var dto = _mapper.Map<CarouselDto>(entity);
                return new Success(dto);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 添加一张轮播图
        /// </summary>
        /// <param name="createDto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<CarouselDto> AddCarousel(CarouselCreateDto createDto)
        {
            try
            {
                var entity = _mapper.Map<CarouselEntity>(createDto);
                if (!_carouselService.AddCarousel(entity))
                {
                    return new Error(new Exception($"添加轮播图失败"));
                }
                return new Success();
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 更新轮播图信息
        /// </summary>
        /// <param name="updateDto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateCarousel(CarouselUpdateDto updateDto)
        {
            var entity = _carouselService.GetCarouselById(updateDto.Id);
            if (entity == null)
            {
                return new Error(new Exception("找不到更新对象"));
            }
            entity = _mapper.Map(updateDto,entity);
            if (!_carouselService.UpdateCarousel(entity))
            {
                return new Error(new Exception("更新失败"));
            }
            return new Success();
        }

        /// <summary>
        /// 删除轮播图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DeleteCarousel(int id)
        {
            if (!_carouselService.DeleteCarousel(id))
            {
                return new Error(new Exception("删除失败"));
            }
            return new Success();
        }

        /// <summary>
        /// 上传轮播图媒体
        /// </summary>
        /// <param name="mediaFile"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> UploadMedia(IFormFile mediaFile)
        {
            try
            {
                if (mediaFile == null)
                {
                    return new Error(new Exception("未上传文件"));
                }

                string mediaType = Path.GetExtension(mediaFile.FileName).ToLower();

                if (mediaType != ".jpg" && mediaType != ".jpeg" && mediaType != ".mp4")
                {
                    return new Error(new Exception("上传的文件格式不支持"));
                }

                if (mediaType == ".jpg" || mediaType == ".jpeg")
                {
                    if (mediaFile.Length > 2 * 1024 * 1024)
                    {
                        return new Error(new Exception("图片大小不能超过2mb"));
                    }
                }

                if (mediaType == ".mp4")
                {
                    if (mediaFile.Length > 6 * 1024 * 1024)
                    {
                        return new Error(new Exception("图片大小不能超过6mb"));
                    }
                }

                string fileName = $"{Guid.NewGuid().ToString()}{mediaType}";
                string folderPath = Path.Combine("wwwroot", "carousel");
                string filePath = Path.Combine("wwwroot", "carousel", fileName);

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                using (FileStream stream = new FileStream(filePath, FileMode.Create))
                {
                    await mediaFile.CopyToAsync(stream);
                }

                string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
                string mediaUrl = $"/carousel/{fileName}";

                return new Success(new { Host = baseUrl, Url = mediaUrl }) ;
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }
    }
}
